<script setup lang="ts">
import {ref, useTemplateRef} from "vue";
import myAxios from "../../plugins/MyAxios.ts";
import {showFailToast, showSuccessToast} from "vant";
import {useRouter} from "vue-router";


const form = useTemplateRef('form');
const username = ref<string>('')
const password = ref<string>('')
const passwordAgain = ref<string>('')

const checkUserName = () => {
  if (username.value === null || username.value === "" || username.value === undefined) {
    return false;
  }else if (username.value.length < 4) {
    return false;
  }
  return true;
}

const checkPassword = () => {
  if (password.value === null || password.value === "" || password.value === undefined) {
    return false;
  }
  if (password.value.length < 8) {
    return false;
  }
  const regex = /[^a-zA-Z0-9]/; // 匹配任何非字母和非数字的字符
  return !regex.test(password.value);
}

const checkPasswordAgain = () => {
  if (passwordAgain.value === null || passwordAgain.value === "" || passwordAgain.value === undefined) {
    return false;
  }
  return password.value === passwordAgain.value;
}

const router = useRouter();
const register = async () => {
  try {
    const formRef = form.value as any;
    await formRef.validate();
    const result = await myAxios.post('/user/register', {
      userAccount : username.value,
      userPassword : password.value,
      checkPassword : passwordAgain.value
    });
    if (result.data.code !== 200) {
      showFailToast('注册失败');
    } else {
      showSuccessToast('注册成功');
      await router.push('/login')
    }
  } catch (e) {
    showFailToast('网络异常');
    console.log(e)
  }
}

const goBack = () => {
  router.push('/login')
}

</script>

<template>
  <div class="form">
    <van-form ref="form">
      <van-cell-group inset>
        <van-field
            v-model="username"
            name="username"
            label="用户账号"
            placeholder="请输入用户账号"
            :rules="[{ required: true, validator : checkUserName ,message: '用户账号长度不小于4' }]"
        />
        <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, validator: checkPassword, message: '密码长度不小于8,不能包含特殊字符' }]"
        />
        <van-field
            v-model="passwordAgain"
            type="password"
            name="passwordAgain"
            label="再次输入密码"
            placeholder="再次输入密码"
            :rules="[{ required: true, validator: checkPasswordAgain, message: '两次密码不同' }]"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" @click="register">
          注册
        </van-button>
      </div>
    </van-form>
    <div style="margin: 16px;">
      <van-button round block type="primary" @click="goBack">
        返回
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.form {
  margin: 150px auto;
}
</style>